<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form ref="queryForm" :model="queryParams" size="small" :inline="true">
      <el-form-item>
        <el-button
          v-has-permission="['sys:generator:add']"
          type="primary"
          icon="el-icon-plus"
          @click="handleDownloadBatch"
        >批量下载代码
        </el-button>
        <el-button
          v-has-permission="['sys:generator:edit']"
          type="success"
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
        >批量修改
        </el-button>
        <el-button
          v-has-permission="['sys:generator:delete']"
          type="danger"
          icon="el-icon-delete"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-form-item>
      <el-form-item prop="tabName">
        <el-input
          v-model="queryParams.tableName"
          placeholder="数据表名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template #default="props">
          <el-form label-position="left" inline class="auiu-table-expand">
            <el-form-item label="实体类名称">
              <span>{{ props.row.className }}</span>
            </el-form-item>
            <el-form-item label="使用的模板">
              <span>{{ props.row.tplCategory }}</span>
            </el-form-item>
            <el-form-item label="包路径">
              <span>{{ props.row.packageName }}</span>
            </el-form-item>
            <el-form-item label="模块名">
              <span>{{ props.row.moduleName }}</span>
            </el-form-item>
            <el-form-item label="业务名">
              <span>{{ props.row.businessName }}</span>
            </el-form-item>
            <el-form-item label="生成代码方式">
              <span>{{ codeGenTypeOptionsFormat(props.row.genType) }}</span>
            </el-form-item>
            <el-form-item label="生成路径">
              <span>{{ props.row.genPath }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="表名" prop="tableName" width="200" />
      <el-table-column label="表描述" prop="tableComment" width="200" />
      <el-table-column label="功能名" prop="functionName" width="200" />
      <el-table-column label="功能作者" prop="functionAuthor" width="200" />
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            v-has-permission="['sys:client:delete']"
            type="warning"
            icon="el-icon-download"
            size="mini"
            circle
            plain
            @click.stop="handleDownload(scope.row)"
          />
          <el-button
            v-has-permission="['sys:generator:edit']"
            type="primary"
            icon="el-icon-edit"
            size="mini"
            circle
            plain
            @click.stop="handleUpdate(scope.row)"
          />
          <el-button
            v-has-permission="['sys:generator:delete']"
            type="danger"
            icon="el-icon-delete"
            size="mini"
            circle
            plain
            @click.stop="handleDelete(scope.row)"
          />
          <el-button
            v-has-permission="['sys:generator:sync']"
            type="success"
            size="mini"
            round
            plain
            @click.stop="syncDb(scope.row)"
          >同步数据表
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pagination.total > 0"
      :total="pagination.total"
      :page.sync="pagination.page"
      :limit.sync="pagination.limit"
      @pagination="handleQuery"
    />

    <!-- 表单弹窗 -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="800px"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row v-if="form.tableId">
          <el-col :span="8">
            <el-form-item label="数据表名称" prop="tableName">
              <el-input v-model="form.tableName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据表描述" prop="tableComment">
              <el-input v-model="form.tableComment" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据表功能" prop="functionName">
              <el-input v-model="form.functionName" placeholder="请输入数据表功能" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="模块名称" prop="moduleName">
              <el-input
                v-model="form.moduleName"
                placeholder="请输入模块名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="业务名称" prop="businessName">
              <el-input
                v-model="form.businessName"
                placeholder="请输入业务名称"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="作者" prop="functionAuthor">
              <el-input
                v-model="form.functionAuthor"
                placeholder="请输入作者"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="14">
            <el-form-item label="包路径" prop="packageName">
              <el-input v-model="form.packageName" placeholder="请输入包路径" />
            </el-form-item>
          </el-col>
          <el-col v-if="form.tableId" :span="10">
            <el-form-item label="实体类名称" prop="className">
              <el-input
                v-model="form.className"
                placeholder="请输入实体类名称"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="使用的模板" prop="tplCategory">
              <el-select v-model="form.tplCategory" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="代码生成路径" prop="genPath">
              <el-input
                v-model="form.genPath"
                placeholder="请输入代码生成路径"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="生成代码方式" prop="genType">
              <el-radio-group v-model="form.genType">
                <el-radio label="0" border>zip压缩包</el-radio>
                <el-radio label="1" border>自定义</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="dialog.visible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { batchGenCode, del, detail, download, list, synchDb, update, updateBatch } from '@/api/admin/generator'
import { list as dictList } from '@/api/admin/dict-item'
import { convertRes2Blob } from '@/utils'

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      tableNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      queryParams: {
        tabName: undefined
      },
      pagination: {
        page: 1,
        limit: 10,
        total: 0
      },
      pageList: [],
      codeGenTypesOptions: [],
      dialog: {
        title: undefined,
        visible: false,
        type: undefined // type 操作类型：1-新增 2-修改
      },
      // 表单参数
      form: {
        genType: '0',
        businessName: undefined,
        className: undefined,
        crud: true,
        functionAuthor: 'dries',
        functionName: undefined,
        genPath: '/',
        moduleName: 'system',
        packageName: 'com.samphanie.auiu',
        params: Object,
        sub: false,
        tableComment: undefined,
        tableId: undefined,
        tableName: undefined,
        tplCategory: 'crud',
        tree: false
      },
      options: [
        {
          value: 'crud',
          label: '单表操作'
        },
        {
          value: 'tree',
          label: '树表操作',
          disabled: true
        },
        {
          value: 'sub',
          label: '主子表操作',
          disabled: true
        }
      ],
      // 表单校验
      rules: {}
    }
  },
  async created() {
    this.handleQuery()
  },
  methods: {
    handleQuery() {
      this.queryParams.pageNum = this.pagination.page
      this.queryParams.pageSize = this.pagination.limit
      list(this.queryParams).then(response => {
        const { data } = response
        this.pageList = data.list
        this.pagination.total = data.totalCount
        this.loading = false
      })

      dictList({ dictCode: 'code_gen_type', queryMode: 'list' }).then(
        response => {
          this.codeGenTypesOptions = response.data
        }
      )
    },
    handleReset() {
      this.pagination = {
        page: 1,
        limit: 10,
        total: 0
      }
      this.queryParams = {
        tableName: undefined
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.tableId)
      this.tableNames = selection.map(item => item.tableName)
      this.single = selection.length <= 1
      this.multiple = !selection.length
    },
    handleDownload(row) {
      download(row.tableName).then(res => {
        if (res) {
          convertRes2Blob(res)
        }
      })
    },
    handleDownloadBatch() {
      const tableNames = this.tableNames.toString()
      batchGenCode({ tables: tableNames }).then(res => {
        if (res) {
          convertRes2Blob(res)
        }
      })
    },
    handleAdd() {
      this.resetForm()
      this.dialog = {
        title: '新增',
        visible: true,
        type: 'add'
      }
    },
    handleUpdate(row) {
      this.resetForm()
      let title = '批量修改生成代码基本信息'
      if (row.tableId) {
        title = '修改生成代码基本信息'
        const tableId = row.tableId
        detail(tableId).then(response => {
          const { data } = response
          this.form = data.info
        })
      }
      this.dialog = {
        title: title,
        visible: true,
        type: 'edit'
      }
    },
    handleDelete(row) {
      const ids = row.tableId ? [row.tableId] : this.ids
      this.$confirm('确认删除已选中的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          del(ids).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
          })
        })
        .catch(() => this.$message.info('已取消删除'))
    },
    handleSubmit: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.dialog.type === 'edit') {
            if (this.genConfig.autoRemovePre === 1 && (this.genConfig.tablePrefix === undefined || this.genConfig.tablePrefix === '')) {
              this.$message.error('请输入去除的表前缀')
              return
            } else {
              this.form.params = this.genConfig
            }
            if (this.form.tableId) {
              update(this.form).then(() => {
                this.$message.success('修改成功')
                this.closeDialog()
                this.handleQuery()
              })
            } else {
              const data = {
                tableNames: this.tableNames,
                tableInfo: this.form
              }
              updateBatch(data).then(() => {
                this.$message.success('修改成功')
                this.closeDialog()
                this.handleQuery()
              })
            }
          }
        }
      })
    },
    syncDb(row) {
      synchDb(row.tableName).then(res => {
        if (res && res.code === 20000) {
          this.$message.success('同步数据库成功')
          this.handleQuery()
        } else {
          this.$message.error('同步数据库失败')
        }
      })
    },
    resetForm() {
      this.form = {
        genType: '0',
        businessName: undefined,
        className: undefined,
        crud: true,
        functionAuthor: 'dries',
        functionName: undefined,
        genPath: '/',
        moduleName: 'system',
        packageName: 'com.samphanie.auiu',
        params: Object,
        sub: false,
        tableComment: undefined,
        tableId: undefined,
        tableName: undefined,
        tplCategory: 'crud',
        tree: false
      }
      if (this.$refs['form']) {
        this.$refs['form'].resetFields()
      }
    },
    // 生成代码方式字典翻译
    codeGenTypeOptionsFormat(row) {
      if (!row) return
      const codeGenType = this.codeGenTypesOptions.filter(
        item => item.value == row
      )
      return codeGenType[0].name
    },
    closeDialog() {
      this.dialog = {
        title: undefined,
        visible: false,
        type: undefined,
        configVisible: false
      }
    }
  }
}
</script>

<style lang="scss">
.auiu-table-expand {
  font-size: 0;

  label {
    width: 100px;
    color: #99a9bf;
  }

  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 30%;
  }
}
</style>
